<script setup lang="ts">
import {inject, type Ref, ref} from 'vue'
import {getCurrentInstance} from "vue";

const global = getCurrentInstance().appContext.config.globalProperties;
const formRef = ref();

//注入全局用户状态
const userState = inject<Ref<{
  id: number;
  username: string;
  password: string;
  phone: string;
  email: string;
  avatar: string
  role: string;
  status: number;
  created_at: string;
  updated_at: string;
}>>('userState')

//用户名称
const userName = ref('欢迎来到海鲜市场')
// 记住密码选项
const rememberMe = ref(false)

//登录方式:手机和和密码
const loginForm = ref({
  phone: '',
  password: ''
})

//勾选协议（
const agreeProtocol = ref(false)

// 关闭登录
const closeLogin = () => {
  console.log('关闭登录')
}

// 忘记密码
const forgotPassword = () => {
  console.log('忘记密码')
}

const rules={
  phone:[
    {required:true,message:'手机号不能为空', trigger: 'blur'},
    {
      pattern:/^1[3-9]\d{9}$/,
      message: '请输入正确的11位手机号',
      trigger: 'blur'
    }
  ],
  password:[
    {required:true,message:'必须输入密码', trigger: 'blur'},
    {
      pattern: /^[A-Za-z0-9!@#$%^&*_]{6,16}$/,
      message: '密码长度在6到16个字符之间,可包含!@#$%^&*_等符号',
      trigger: 'blur'
    }
  ]
}

//处理登录
const handleLogin = () => {
  // 先触发表单校验
  formRef.value.validate((valid) => {
    if (!valid) {
      global.$message.warning('请完善登录信息');
      return;
    }

    // 打印表单数据，调试用
    console.log('提交登录', loginForm.value);

    // 发请求
    global.$http({
      url: '/backend/login',
      method: 'POST',
      data: {
        phone: loginForm.value.phone,
        password: loginForm.value.password,
        // rememberMe: rememberMe.value, //
      }
    })
        .then((res) => {
          // 根据后端返回判断登录成功与否，举例:
          if (res.data.code === 200) {
            const currentUser = res.data.data; // 后端返回的 user 对象

            // 存储到全局用户状态
            if (userState) {
              userState.value = currentUser;
            }

            // 持久化存储
            localStorage.setItem('user', JSON.stringify(currentUser));

            global.$message.success(res.data.msg || '登录成功');

            //获取后端返回的 user 属性
            const userInfo = res.data.data;

            //存储到全局状态
            if (userState) {
              userState.value = userInfo; //存入全局状态
            }
            if (res.data.data.role==="user") {
              global.$router.push('/home'); // 登录成功跳首页}
            }else
            {
              global.$router.push('/home');
            }
          } else {
            global.$message.error(res.data.msg || '登录失败');
          }
        })
        .catch((err) => {
          console.error('登录失败:', err);
          global.$message.error('登录请求失败，请稍后重试');
        });
  });
};

</script>

<template>
  <div class="login-container">
    <!-- 顶部操作区 -->
    <div class="header">
      <el-icon @click="closeLogin" class="close-icon">
        <Close />
      </el-icon>
      <el-dropdown>
        <span class="el-dropdown-link">
          更多 <el-icon><ArrowDown /></el-icon>
        </span>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item>帮助中心</el-dropdown-item>
            <el-dropdown-item>意见反馈</el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
    </div>

    <!-- 用户信息区 -->
    <div class="user-info">

      <div class="avatar-container">
        <img src="../Login/闲鱼.jpg" alt="闲鱼头像" class="avatar" />
      </div>
      <div class="username">{{ userName }}</div>
    </div>

    <!-- 登录表单 -->
    <el-form :model="loginForm"
             :rules="rules"
             ref="formRef"
             class="login-form">

      <el-form-item prop="phone">
        <el-input v-model="loginForm.phone"
                  placeholder="手机号/邮箱"
                  prefix-icon="User" />
      </el-form-item>

      <el-form-item prop="password">
        <el-input
            v-model="loginForm.password"
            type="password"
            placeholder="请输入密码"
            prefix-icon="Lock"
        >
          <template #append>
            <el-link type="primary" @click="forgotPassword" style="font-size: 12px;">忘记密码？</el-link>
          </template>
        </el-input>
      </el-form-item>

      <el-form-item>
        <el-button
            id="btn"
            type="primary"
            :disabled="!agreeProtocol"
            @click="handleLogin"
            class="login-button"
        >
          登录
        </el-button>
        <el-button id="btn">
          <router-link :to="'/signMenu'" class="register-link">注册</router-link>
        </el-button>
      </el-form-item>
    </el-form>

    <el-form>
      <el-form-item class="choice">
        <el-checkbox class="choice1" v-model="rememberMe">记住密码</el-checkbox>
        <el-checkbox class="choice2" v-model="agreeProtocol">我已阅读并同意用户协议</el-checkbox>
      </el-form-item>
    </el-form>
  </div>

</template>


<style scoped>
.login-container{
  margin: 0px 10px;
}

.header {
  display: flex;
  width: 100%;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.close-icon {
  cursor: pointer;
  font-size: 18px;
  color: #000000;
}

.el-dropdown-link {
  cursor: pointer;
  color: #409eff;
  font-size: 14px;
}

.user-info {
  text-align: center;
  margin-bottom: 30px;
}

.avatar-container {
  width: 80px;
  height: 80px;
  margin: 0 auto 10px;
  border-radius: 50%;
  overflow: hidden;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
}

.avatar {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.username {
  font-size: 18px;
  font-weight: bold;
  color: #333;
}

.login-form {
  padding: 0;
}

.form-item-right {
  text-align: right;
}

.login-button {
  width: 100%;
  color: #eeeeee;
}

.register-link {
  display: flex;
  align-items: center;
  color: #eeeeee !important;
  cursor: pointer;
}

.register-link {
  font-size: 14px;
  color: #409eff;
  text-decoration: none;
}

#btn{
  display: flex;
  width: 48%;
  background-color: #409eff;
}

.choice {
  position: relative;
}

.choice1{
  position: absolute;
  left: 0px;
}

.choice2{
  position: absolute;
  right: 5px;
}

</style>
